package com.pgeneral.user.management.service.impl;

import com.pgeneral.user.management.dao.UserDepartmentinfoMapper;
import com.pgeneral.user.management.dao.UserSoproleMapper;
import com.pgeneral.user.management.dto.GlobalInfosDTO;
import com.pgeneral.user.management.entity.UserDepartmentInfo;
import com.pgeneral.user.management.exception.MyException;
import com.pgeneral.user.management.util.FileStoreUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.pgeneral.user.management.entity.UserUserInfo;
import com.pgeneral.user.management.dao.UserUserinfoMapper;
import com.pgeneral.user.management.service.UserUserinfoService;
import org.springframework.transaction.annotation.Transactional;

import static com.pgeneral.user.management.constant.URLConstantUtils.SIGN_FILE_PATH;
import static java.awt.SystemColor.info;

@Slf4j
@Service
public class UserUserinfoServiceImpl implements UserUserinfoService {

    @Resource
    private UserUserinfoMapper dao;

    @Resource
    private UserSoproleMapper userSoproleMapper;

    @Resource
    private UserDepartmentinfoMapper userDepartmentinfoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchInsert(List<UserUserInfo> userInfos) {
        if (userInfos != null && !userInfos.isEmpty()) {
            if (knowledgeIsRepeat(userInfos)) {
                throw new MyException("1001", "登录名重复，请重新修改!");
            }
            Date data = new Date();
            //文件路径
            String path = SIGN_FILE_PATH + new SimpleDateFormat("yyyy/MM").format(data);
            userInfos.forEach(item -> {
                if (item.getUserName() != null && !"".equals(item.getUserName())) {
                    int i = dao.getRepatData(item.getUserName(), null);
                    if (i > 0) {
                        throw new MyException("1001", "登录名重复，请重新修改!");
                    }
                }
                log.info("文件路径为：{}", path);
                if (item.getMessage() != null && !("").equals(item.getMessage())) {
                    boolean b = FileStoreUtils.createFile(path);
                    if (b) {
                        String filePath = path + File.separator + item.getUserId() + ".txt";
                        item.setPath(filePath);
                        FileStoreUtils.saveFileMessage(filePath, item.getMessage());
                    }

                }
            });
            return dao.batchInsert(userInfos);
        }
        throw new MyException("1001", "请输入用户参数!");
    }

    /**
     * 判断List<UserInfo>的对象code是否有重复，有重复true
     *
     * @param orderList
     * @return
     */
    private Boolean knowledgeIsRepeat(List<UserUserInfo> orderList) {
        Set<UserUserInfo> set = new TreeSet<>(Comparator.comparing(UserUserInfo::getUserName));
        set.addAll(orderList);
        if (set.size() < orderList.size()) {
            return true;
        }
        return false;
    }

    @Override
    public List<UserUserInfo> getUserInfo(UserUserInfo userInfo) {
        return dao.getUserInfo(userInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserInfoTable(UserUserInfo userInfo) {
        if (userInfo.getUserName() != null && !"".equals(userInfo.getUserName())) {
            int i = dao.getRepatData(userInfo.getUserName(), userInfo.getUserId());
            if (i > 0) {
                throw new MyException("1001", "登录名重复，请重新修改!");
            }
        }
        Date data = new Date();
        //文件路径
        String path = SIGN_FILE_PATH + new SimpleDateFormat("yyyy/MM").format(data);
        log.info("文件路径为：{}", path);
        //如果参数签名信息不为空
        if (userInfo.getMessage() != null && !("").equals(userInfo.getMessage())) {
            boolean b = FileStoreUtils.createFile(path);
            if (b) {
                String filePath = path + "/" + userInfo.getUserId() + ".txt";
                userInfo.setPath(filePath);
                FileStoreUtils.saveFileMessage(filePath, userInfo.getMessage());
            }
        }
        return dao.updateUserInfoBySign(userInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateIsDeletefromUserInfoTable(List<String> ids) {
        return dao.updateIsDeletefromUserInfoTable(ids);
    }

    @Override
    public List<GlobalInfosDTO> getGlobalInfos(UserUserInfo userInfo) {
        return dao.getGlobalInfos(userInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updatePasswordByUserId(UserUserInfo userInfo) {
        return dao.updatePasswordByUserId(userInfo);

    }

    @Override
    public List<GlobalInfosDTO> getThreeTable(UserUserInfo userInfo) {
        return dao.getThreeTable(userInfo);
    }

    @Override
    public List<GlobalInfosDTO> getLoginUser(UserUserInfo userInfo) {
        if (userInfo.getUserName() == null || "".equals(userInfo.getUserName()) || userInfo.getPasswordWord() == null || "".equals(userInfo.getPasswordWord())) {
            throw new MyException("1002", "用户名或密码不能为空！");
        }
//        List<GlobalInfosDTO> loginUser = dao.getLoginUserForPaid(userInfo);
        //查询用户信息
        UserUserInfo userUserInfo = dao.validatePassword(userInfo);
        if (userUserInfo != null) {
            //获取用户多个角色ID
            List<String> roleIds = Arrays.asList(userUserInfo.getRoleId().split(";"));
            List<GlobalInfosDTO> userSopRoleScopes = userSoproleMapper.getUserSopRoleScopes(roleIds);
            if (!userSopRoleScopes.isEmpty()) {
                GlobalInfosDTO globalInfosDTO = userSopRoleScopes.get(0);
                BeanUtils.copyProperties(userUserInfo, globalInfosDTO);
                if (userUserInfo.getDepartmentId() != null) {
                    UserDepartmentInfo infoByDepartmentId = userDepartmentinfoMapper.getInfoByDepartmentId(userUserInfo.getDepartmentId());
                    BeanUtils.copyProperties(infoByDepartmentId, globalInfosDTO);
                }
            }
            return userSopRoleScopes;
        }

        return new ArrayList<>();
    }

    @Override
    public List<UserUserInfo> getSign(String userId, String userName) {
        List<UserUserInfo> info = new ArrayList<>();
        if ((userId == null || ("").equals(userId)) && (userName == null || ("").equals(userName))) {
            return info;
        }
        List<Map<String, String>> sign = dao.getSign(userId, userName);

        sign.forEach(s -> {
            UserUserInfo userInfo = new UserUserInfo();
            if (s.get("path") != null) {
                String messages = FileStoreUtils.getFileMessages(s.get("path"));
                userInfo.setMessage(messages);
            }
            userInfo.setUserName(s.get("UserName"));
            info.add(userInfo);
        });
        return info;
    }

    @Override
    public List<UserUserInfo> getSignByUserNames(List<String> userName) {
        List<UserUserInfo> info = new ArrayList<>();
        List<Map<String, String>> signByUserNames = dao.getSignByUserNames(userName);

        signByUserNames.forEach(s -> {
            UserUserInfo userInfo = new UserUserInfo();
            if (s.get("path") != null) {
                String messages = FileStoreUtils.getFileMessages(s.get("path"));
                userInfo.setMessage(messages);
            }
            userInfo.setUserName(s.get("UserName"));
            info.add(userInfo);
        });
        return info;
    }
}
